package preorder

import (
	"time"
	"encoding/json"
	"dhfshop/controllers/base"
	"dhfshop/domain/preorder"
	"dhfshop/models/preorder"
	"github.com/astaxie/beego"
	//"dhfshop/models/consts"
	"github.com/astaxie/beego/validation"
)

type STLToDataController struct {
	base.BaseController
}

func (this *STLToDataController) Post() {
	v := struct {
		PartnerId  int64  `form:"-"`
		ResItemId  int64  `form:"res_item_id"`
	}{}
	v.PartnerId = int64(this.Ctx.Input.GetData("curCompanyId").(int))
	this.ParseForm(&v)
	valid := validation.Validation{}
	valid.Required(v.ResItemId, "res_item_id")
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key + " " + valid.Errors[0].Message)
		return
	}
	resItem, err := preorder.GetResItemById(v.ResItemId)
	if err != nil {
	    this.ServeError(err.Error())
		return
	}
	templateHub, err := preorderlayer.TemplateToHub(v.PartnerId, resItem.StoreId, resItem.TemplateId)
	if err != nil {
	    this.ServeError(err.Error())
		return
	}
	b, _ := json.Marshal(templateHub)
	beego.Debug(string(b))
	defaultReserveDays := 7 
	if opt, err := preorder.GetPreOrderOptByPartnerId(v.PartnerId, resItem.StoreId); err == nil {
	    defaultReserveDays = opt.CanReserveDays
	}
	periods, err := preorderlayer.ModelToMultiDay(v.ResItemId, templateHub, defaultReserveDays)
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	for _, period := range periods {
	    preorder.AddPeriods(period)
	    preorder.AddMultiTimeslots(period.Timeslots)
	}
	rsp := struct {
		ResItemId  int64     `json:"res_item_id"`
		Created   time.Time `json:"created"`
	}{ResItemId: v.ResItemId, Created: time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}


